It is often necessary for computer programs to dynamically allocate memory during the execution of an algorithm. In many cases, the memory is allocated from either the stack or the heap. As is known, a stack or stack frame is a temporary memory allocation that is set up by a memory allocator (for example, by a function when the function is called) and lasts as long as the allocator of the stack. The allocator can use the stack to temporarily hold objects, including local variables and arguments, for as long as the allocator exists. Objects that are allocated to the stack typically are deallocated on or before deallocation of the stack. If an object in the stack is not deallocated along with the stack, then there is considered to be a memory leak. Memory allocators include, but are not limited to, function prologues and constructors. Memory deallocators include, but are not limited to, function epilogues and destructors.
Since objects allocated to the stack typically are deallocated with the stack, those objects preferably should be limited to the scope of their allocators and the stack. For example, an object should be local to its allocator and not global, otherwise a problem may occur when the object is deallocated along with the stack. When objects are global or are desired to exist for a long period of time, those objects typically are allocated to the heap instead of the stack. The heap is reserved for the memory allocation requirements of the computer program, and is separate from the stack. Unlike the stack, the heap's lifetime is not limited to the lifetime of an allocator.
As stack allocation is faster than heap allocation, it may be desirable to use stack allocation instead of heap allocation; however, computer programs typically cannot determine the lifetime of an object to be allocated to memory. Therefore, computer programs typically default the object's allocation to the heap. Further, computer programs and programming languages typically lack mechanisms for specifying stack allocation instead of heap allocation, and also typically lack mechanisms for specifying an allocation that uses the stack when possible and uses the heap otherwise. Accordingly, memory allocation to the stack typically is not optimized, resulting in low computing efficiency.